﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;
using System.Collections;
using System.IO;

namespace WebCommit.Common.Helpers
{
	public class NHibernateHelper
	{
		private static Hashtable sessionTable = new Hashtable();
		private static Hashtable factoryTable = new Hashtable();

		static NHibernateHelper()
		{
			string path = Utility.GetCurrentAppPath() + "\\Config\\HibernateConfig\\";
			string[] factoryFiles = Directory.GetFiles(path);
			foreach (string factoryFileName in factoryFiles)
			{
				FileInfo info = new FileInfo(factoryFileName);
				string hmbCfgDirName = info.Name.Split('.')[0];
				string hbmPath = path + hmbCfgDirName + "\\";
				Configuration cfg = new Configuration();
				string[] hbmFiles = Directory.GetFiles(hbmPath);
				cfg = cfg.Configure(factoryFileName);
				foreach (string hbmFileName in hbmFiles)
				{
					cfg.AddFile(hbmFileName);
				}
				ISessionFactory factory = cfg.BuildSessionFactory();
				factoryTable.Add(hmbCfgDirName.ToUpper(), factory);
			}
		}

		public static ISession GetSession(string factoryName)
		{
			factoryName = factoryName.ToUpper();
			ISession session = sessionTable[factoryName] as ISession;
			if (session != null)
			{
				return session;
			}
			else
			{

				ISessionFactory factory = factoryTable[factoryName] as ISessionFactory;
				if (factory != null)
				{
					session = factory.OpenSession();
					sessionTable.Add(factoryName, session);
					return session;
				}
				else
				{
					return null;
				}
			}

			//ISession currentSession = sessionTable[DefaultSessionKey] as ISession;

			//if (currentSession == null)
			//{
			//    currentSession = sessionFactory.OpenSession();
			//    sessionTable[DefaultSessionKey] = currentSession;
			//}

			//return currentSession;
		}

	}

}
